package com.simtop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.ServerResponse;
import com.simtop.expection.GlobalException;
import com.simtop.pojo.Sqsy;
import com.simtop.pojo.User;
import com.simtop.pojo.experiment.Experiment;
import com.simtop.pojo.experiment.ExperimentDynamicVo;
import com.simtop.pojo.experiment.ExperimentReportVo;
import com.simtop.service.ExperimentService;
import com.simtop.util.JwtUtil;
import org.python.antlr.ast.Str;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author lvyongwei
 */
@CrossOrigin
@RestController
@RequestMapping("/experiment")
public class ExperimentController {

    @Autowired
    private ExperimentService experimentService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 点赞存储的键名
     */
    private static final String KEY = "editorCheck:giveLike:";


    /**
     * 提交成绩
     * @param experiment
     * @param request
     * @return
     */
    @PostMapping("/add")
    public ServerResponse add(@RequestBody Experiment experiment, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            experiment.setUserId(u.getId());
            boolean flag = experimentService.insertExperiment(experiment);
            if(flag==false){
                return ServerResponse.createByErrorMsg("提交内容失败");
            }
            return ServerResponse.createBySuccessMsg("提交内容成功");
        } catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("提交内容失败");
        }
    }

    /**
     * 修改提交内容
     * @param experiment
     * @param request
     * @return
     */
    @PostMapping("/update")
    public ServerResponse update(@RequestBody Experiment experiment, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            experimentService.updateExperiment(experiment);
            return ServerResponse.createBySuccessMsg("修改成绩成功");
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("修改成绩失败");
        }
    }

    /**
     * 查看实验动态(即每个人都能看到其他所有人)
     * @param experimentDynamicVo
     * @param request
     * @return
     */
    @PostMapping("/getDynamic")
    public ServerResponse getDynamic(@RequestBody ExperimentDynamicVo experimentDynamicVo, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            PageHelper.startPage(experimentDynamicVo.getPageNum(),experimentDynamicVo.getPageSize());
            List<ExperimentDynamicVo> allDynamic = experimentService.getAllDynamic(experimentDynamicVo.getMessage());
            allDynamic.forEach(
                    a -> {
                        a.setGiveLike(redisTemplate.opsForSet().size(KEY + a.getExperimentId()));
                        a.setIfGiveLike(redisTemplate.opsForSet().isMember(KEY + a.getExperimentId(),u.getId()));
                    }
            );
            PageInfo<ExperimentDynamicVo> pageInfo = new PageInfo<>(allDynamic);
            return ServerResponse.createBySuccess("获取动态成功",pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("获取动态失败");
        }
    }


    /**
     * 查看实验报告列表
     * @param experimentDynamicVo
     * @param request
     * @return
     */
    @PostMapping("/getReport")
    public ServerResponse getReport(@RequestBody ExperimentDynamicVo experimentDynamicVo, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            //判断不是管理员和教师身份
            if (!u.getRoleId().equals(1) && !u.getRoleId().equals(2)) {
                PageHelper.startPage(experimentDynamicVo.getPageNum(),experimentDynamicVo.getPageSize());
                List<ExperimentReportVo> allReport = experimentService.getAllReport(u.getId(),experimentDynamicVo.getMessage());
                PageInfo<ExperimentReportVo> pageInfo = new PageInfo<ExperimentReportVo>(allReport);
                return ServerResponse.createBySuccess("获取实验报告成功",pageInfo);
            }
            PageHelper.startPage(experimentDynamicVo.getPageNum(),experimentDynamicVo.getPageSize());
            List<ExperimentReportVo> allReport = experimentService.getAllReport(null,experimentDynamicVo.getMessage());
            PageInfo<ExperimentReportVo> pageInfo = new PageInfo<ExperimentReportVo>(allReport);
            return ServerResponse.createBySuccess("获取实验报告成功",pageInfo);
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("获取实验报告成功");
        }
    }
    /**
     * 查看实验报告
     * @param
     * @param
     * @return
     */
    @PostMapping("/subExperimental")
    public ServerResponse subExperimental(@RequestBody Sqsy sqsy, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }

        try{
            //拿到 用户id
            Integer sqsyuserid = u.getId();
            //拿到yonghu名称
            String sqsyname = u.getUsername();
            //实验详情
            String sqsyxq = sqsy.getExperimentalDetails();

            String sqsypj = sqsy.getExperimentalEvaluate();

            String sqsysc = sqsy.getExperimentOften();

            int sqsyzf = sqsy.getExperimentalTotal();

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String sqsysj = df.format(new Date());

            experimentService.tjcj(sqsyuserid,sqsyname,sqsyxq,sqsypj,sqsysc,sqsyzf,sqsysj);

            return ServerResponse.createBySuccess("提交实验报告成功");
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("提交实验报告失败");
        }
    }

    /**
     * 查看实验报告
     * @param
     * @param
     * @return
     */
    @PostMapping("/findExperimental")
    @ResponseBody
    public ServerResponse findExperimental(@RequestBody ExperimentDynamicVo experimentDynamicVo, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        //System.out.println(u.getId());
        //System.out.println(u.getRoleId());
        try{
            //判断不是管理员和教师身份
            if (!u.getRoleId().equals(1) && !u.getRoleId().equals(2)) {
                PageHelper.startPage(experimentDynamicVo.getPageNum(),experimentDynamicVo.getPageSize());
                //只找自己\
                System.out.println(u.getId());
                List<Sqsy> allsy = experimentService.allsy(u.getId());
                PageInfo<Sqsy> pageInfo = new PageInfo<Sqsy>(allsy);
                return ServerResponse.createBySuccess("获取实验报告成功",pageInfo);
            }
            PageHelper.startPage(experimentDynamicVo.getPageNum(),experimentDynamicVo.getPageSize());
            //List<ExperimentReportVo> allReport = experimentService.getAllReport(null,experimentDynamicVo.getMessage());
            //全查
            List<Sqsy> allallsy = experimentService.allallsy();
            PageInfo<Sqsy> pageInfo = new PageInfo<Sqsy>(allallsy);
            return ServerResponse.createBySuccess("获取实验报告成功",pageInfo);
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("获取实验报告失败");
        }
    }

    @PostMapping("/deleteExperimental")
    public ServerResponse deleteExperimental(@RequestBody String data, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }

        try{
            JSONObject jsonObject = JSON.parseObject(data);
            int experimentId = jsonObject.getInteger("experimentId");
            experimentService.deleteExperimental(experimentId);
            return ServerResponse.createBySuccess("删除实验报告成功");
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("删除实验报告成功");
        }
    }



    /**
     * 点赞
     */
    @PostMapping("/giveLike")
    public ServerResponse giveLike(@RequestBody String data,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            JSONObject jsonObject = JSONObject.parseObject(data);
            Long id = jsonObject.getLong("experimentId");
            redisTemplate.opsForSet().add(KEY + id,u.getId());
            return ServerResponse.createBySuccessMsg("点赞成功");
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("点赞失败");
        }
    }


    /**
     * 删除实验报告
     */
    @PostMapping("/delete")
    public ServerResponse delete(@RequestBody String data,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            JSONObject jsonObject = JSONObject.parseObject(data);
            Long id = jsonObject.getLong("experimentId");
            experimentService.delete(id);
            return ServerResponse.createBySuccessMsg("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("删除失败");
        }
    }
}